import random
import string
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from hostmanager.models import Host, HostStatistics

def make_password(length=12):
    """生成随机密码"""
    if length < 12:
        length = 12
    characters = string.ascii_letters + string.digits + string.punctuation
    return ''.join(random.choice(characters) for i in range(length))


class Command(BaseCommand):
    help = 'Change host passwords every 8 hours'

    def handle(self, *args, **options):
        hosts = Host.objects.filter(is_active=True)
        for host in hosts:
            new_password = make_password()
            host.root_password = new_password
            host.save()
            self.stdout.write(self.style.SUCCESS(f'Successfully changed password for {host.ip_address}'))


class DailyHostStatisticsCommand(BaseCommand):
    help = '统计每日主机数量'

    def handle(self, *args, **kwargs):
        # 获取当前时间
        now = datetime.now()
        
        # 统计所有主机数量
        total_hosts = Host.objects.filter(is_active=True).count()
        
        # 按城市统计
        city_stats = {}
        cities = City.objects.all()
        for city in cities:
            city_count = Host.objects.filter(is_active=True, data_center__city=city).count()
            city_stats[city.name] = city_count
        
        # 按机房统计
        dc_stats = {}
        data_centers = DataCenter.objects.all()
        for dc in data_centers:
            dc_count = Host.objects.filter(is_active=True, data_center=dc).count()
            dc_stats[f"{dc.city.name}-{dc.name}"] = dc_count
        
        # 保存统计数据到数据库
        HostStatistics.objects.create(
            date=now.date(),
            total_hosts=total_hosts,
            stats={
                'by_city': city_stats,
                'by_data_center': dc_stats
n            }
        )
        
        self.stdout.write(self.style.SUCCESS('Successfully recorded daily host statistics'))